package com.zmn.oms.third.taobao.service.impl;

import com.alibaba.fastjson.JSON;
import com.zmn.base.plat.engine.common.constant.DubboConsts;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.oms.business.interfaces.log.OrderLogBService;
import com.zmn.oms.business.interfaces.notifylog.OrderNotifyLogBService;
import com.zmn.oms.business.interfaces.remark.OrderRemarkBService;
import com.zmn.oms.business.interfaces.tmall.OrderTmallExtendBService;
import com.zmn.oms.business.interfaces.warn.OrderWarnBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderDutyConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.model.entity.log.OrderLog;
import com.zmn.oms.model.entity.master.OrderMaster;
import com.zmn.oms.model.entity.notifylog.OrderNotifyLog;
import com.zmn.oms.model.entity.tamllextend.OrderTmallExtend;
import com.zmn.oms.model.entity.warn.OrderWarn;
import com.zmn.oms.model.entity.warn.OrderWarnReplyEvent;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkLogChange;
import com.zmn.oms.model.vo.remark.OrderRemarkDetailVO;
import com.zmn.oms.model.vo.remark.OrderRemarkVO;
import com.zmn.oms.model.vo.work.ZsOrderWorkVO;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.master.OrderMasterService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.third.base.constant.OrderReasonConsts;
import com.zmn.oms.third.base.util.MasterPhoneUtil;
import com.zmn.oms.third.taobao.TaobaoMapper;
import com.zmn.oms.third.taobao.TaobaoTmcConstants;
import com.zmn.oms.third.taobao.TmallApiInvoker;
import com.zmn.oms.third.taobao.dto.UnservedWarningDTO;
import com.zmn.oms.third.taobao.dto.api.ApiInvokParams;
import com.zmn.oms.third.taobao.dto.api.OrderStatusParams;
import com.zmn.oms.third.taobao.dto.api.ReserveFailedParams;
import com.zmn.oms.third.taobao.dto.api.TmallApiInvokResult;
import com.zmn.oms.third.taobao.service.TmallService;
import com.zmn.oms.zmn.aop.OrderWorkLogUtils;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：
 *
 * @author LiangHailong
 * @date 2019/09/20 15:54
 */
@Service
@Slf4j
public class TmallServiceImpl implements TmallService {
    @Autowired
    private OrderMasterService orderMasterService;
    @Autowired
    private OrderRemarkBService orderRemarkBService;
    @Autowired
    private OrderNotifyLogBService orderNotifyLogBService;
    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderWarnBService orderWarnBService;
    @Autowired
    protected ZsOrderWorkQueryBService zsOrderWorkQueryBService;
    @Autowired
    private OrderLogBService orderLogBService;
    @Autowired
    private OrderTmallExtendBService orderTmallExtendBService;

    //@Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
   // EngineerTmallExpandListRemoteService engineerTmallExpandListRemoteService;
    //@Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
   // EngineerTmallExpandModifyRemoteService engineerTmallExpandModifyRemoteService;

    /**
     * 拉取未服务预警信息
     * @param endTime
     * @return
     */
    public void pullOrderWarns(Date endTime) {
        // 从天猫接口拉取预警信息
        TmallApiInvokResult<UnservedWarningDTO> taobaoApiInvokResult = TmallApiInvoker.pullOrderWarns(endTime);
        if (!taobaoApiInvokResult.isSuccess() || taobaoApiInvokResult.getItems() == null) {
            return;
        }

        // 去除已入库的预警信息
        List<UnservedWarningDTO> newWarns = filterDuplicateUnserviceWarnings(taobaoApiInvokResult.getItems());
        if (newWarns.isEmpty()) {
            return;
        }

        // 保存预警信息
        for (UnservedWarningDTO dto : newWarns) {
            saveWarnInfo(dto);
        }
    }

    /**
     * 同步预约时间
     * @param orderId
     * @param mqMsgKey 自定义标识，对应orderNotifyLog中的mqMsgKey字段，可以为空。
     */
    @Override
    public void syncDutyTime(Long orderId, String mqMsgKey) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);
        if (orderWork == null || orderWork.getDutyTime() == null) {
            return;
        }

        OrderStatusParams params = new OrderStatusParams();
        params.setChannleId(orderWork.getChannelId());
        params.setTmallOrderId(Long.parseLong(orderWork.getOuterId()));
        params.setZmnOrderId(orderId);

        // 预约时间
        Date dutyTime = orderWork.getDutyTime();
        params.setDutyTime(dutyTime);

        // 天猫B端逻辑：预约时间跟工程师是同时传的，预约时间跟派单使用的接口跟参数相同
        boolean isTmallBusiness = TaobaoMapper.isTmallBizChannel(orderWork.getChannelId());
        Integer masterId = orderWork.getMasterId();
        if (isTmallBusiness && masterId != null) {
            OrderMaster master = findOrderMaster(orderId, masterId);
            if (master != null) {
                params.setMasterName(master.getMasterName());
                params.setMasterPhone(MasterPhoneUtil.getSafeMasterPhone(orderWork.getCityId()));
            }
        }

        TmallApiInvokResult result = TmallApiInvoker.pushOrderDutyTime(params);

        // 保存同步记录
        OrderWorkLogChange orderWorkLogChange = new OrderWorkLogChange();
        orderWorkLogChange.setMqMsgKey(mqMsgKey);
        orderWorkLogChange.setOrderId(orderId);
        orderWorkLogChange.setChannelId(orderWork.getChannelId());
        orderWorkLogChange.setStatus(orderWork.getStatus());
        orderWorkLogChange.setResultStatus(orderWork.getResultStatus());
        saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_CONFIRM, result);
    }

    /**
     * 同步预约时间
     * @param orderWorkLogChange
     */
    @Override
    public void syncDutyTime(OrderWorkLogChange orderWorkLogChange) {
        Long orderId = orderWorkLogChange.getOrderId();
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);
        OrderStatusParams params = new OrderStatusParams();
        params.setChannleId(orderWork.getChannelId());
        params.setTmallOrderId(Long.parseLong(orderWork.getOuterId()));
        params.setZmnOrderId(orderId);

        // 预约时间
        Date dutyTime = Optional.ofNullable(orderWorkLogChange.getDutyTime()).orElse(orderWork.getDutyTime());
        if (dutyTime == null) {
            return;
        }
        params.setDutyTime(dutyTime);

        // 天猫B端逻辑：预约时间跟工程师是同时传的，预约时间跟派单使用的接口跟参数相同
        boolean isTmallBusiness = TaobaoMapper.isTmallBizChannel(orderWork.getChannelId());
        Integer masterId = orderWork.getMasterId();
        if (isTmallBusiness && masterId != null) {
            OrderMaster master = findOrderMaster(orderId, masterId);
            if (master != null) {
                params.setMasterName(master.getMasterName());
                params.setMasterPhone(MasterPhoneUtil.getSafeMasterPhone(orderWork.getCityId()));
            }
        }

        TmallApiInvokResult result = TmallApiInvoker.pushOrderDutyTime(params);

        saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_CONFIRM, result);
    }

    /**
     * 同步预约失败
     *
     * @param orderWorkLogChange
     */
    @Override
    public void syncReserveFailed(OrderWorkLogChange orderWorkLogChange) {
        Long orderId = orderWorkLogChange.getOrderId();
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);
        if (orderWork == null || orderWork.getNextContactTime() == null) {
            return;
        }
        // 失败状态为预约失败
        if (!Objects.equals(OrderDutyConsts.DUTY_STATUS_FAIL, orderWork.getDutyStatus())) {
            return;
        }
        //天猫勤鸽单
        if (!Objects.equals(OrderConsts.CHANNEL_ID_TMALL_WYG, orderWork.getChannelId())) {
            return;
        }

        //失败原因
        String reasonCodeName = OrderReasonConsts.getReserveFailedReasonCodeName(NumberUtil.isNullOrZero(orderWork.getDutyFailCode()) ?
                GlobalConsts.NO : orderWork.getDutyFailCode() - 1);
        ReserveFailedParams params = new ReserveFailedParams();
        params.setChannleId(orderWork.getChannelId());
        params.setTmallOrderId(Long.parseLong(orderWork.getOuterId()));
        params.setZmnOrderId(orderId);
        params.setGmtNextContact(orderWork.getNextContactTime());
        params.setFailCode((long)orderWork.getDutyFailCode());
        params.setFailDesc(reasonCodeName);

        TmallApiInvokResult result = TmallApiInvoker.pushReserveFailed(params);

        saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_CONFIRM, result);
    }


    /**
     * 同步挂起
     *
     * @param orderWorkLogChange
     */
    @Override
    public void syncHangUp(OrderWorkLogChange orderWorkLogChange){
        Long orderId = orderWorkLogChange.getOrderId();
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);
        if (orderWork == null || orderWork.getNextContactTime() == null) {
            return;
        }

        Integer dutyFailCode = NumberUtil.isNullOrZero(orderWorkLogChange.getReasonCode()) ? GlobalConsts.NONE : orderWorkLogChange.getReasonCode() - 1;
        String reasonCodeName = OrderReasonConsts.getReserveFailedReasonCodeName(dutyFailCode);

        ReserveFailedParams params = new ReserveFailedParams();
        params.setChannleId(orderWork.getChannelId());
        params.setTmallOrderId(Long.parseLong(orderWork.getOuterId()));
        params.setZmnOrderId(orderId);
        params.setGmtNextContact(orderWorkLogChange.getNextContactTime());
        params.setFailCode((long)dutyFailCode);
        params.setFailDesc(reasonCodeName);

       // TmallApiInvokResult result = TmallApiInvoker.pushHangUp(params);
        // 挂起同步预约失败
        TmallApiInvokResult result = TmallApiInvoker.pushReserveFailed(params);
        saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_CONFIRM, result);

    }

    /**
     * 同步工程师信息
     *
     * @param orderWorkLogChange
     */
    @Override
    public void syncMaster(OrderWorkLogChange orderWorkLogChange) {
        Long orderId = orderWorkLogChange.getOrderId();
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);

        OrderStatusParams params = new OrderStatusParams();
        params.setChannleId(orderWork.getChannelId());
        params.setTmallOrderId(Long.parseLong(orderWork.getOuterId()));
        params.setZmnOrderId(orderId);

        // 领单工程师
        Integer masterId = orderWork.getMasterId();
        OrderMaster master = findOrderMaster(orderId, masterId);

        TmallApiInvokResult result = null;

        // 是否是勤鸽渠道
        boolean isTmallWYG = Objects.equals(OrderConsts.CHANNEL_ID_TMALL_WYG, orderWork.getChannelId());
        // 是否是天猫B端渠道
        boolean isTmallBusiness = TaobaoMapper.isTmallBizChannel(orderWork.getChannelId());

        // 天猫B端逻辑：预约时间跟工程师是同时传的，预约时间跟派单使用的接口跟参数相同
        if (isTmallBusiness) {
            Date dutyTime = Optional.ofNullable(orderWorkLogChange.getDutyTime()).orElse(orderWork.getDutyTime());
            if (dutyTime != null) {
                params.setDutyTime(dutyTime);
            }

            if (master != null) {
                params.setMasterName(
                        Optional.ofNullable(master.getMasterName())
                                .filter(name -> name.length() >= 1)
                                .map(name -> String.format("%s工程师", name.substring(0,1)))
                                .orElse("工程师")
                );
                params.setMasterPhone(
                        Optional.ofNullable(orderDetailService.findOrderDetailByKey(orderWork.getOrderId()))
                                .map(orderDetail -> {
                                    if (Objects.equals(orderDetail.getBindStatus(), OrderConsts.BIND_STATUS_BIND)
                                            && org.apache.commons.lang3.StringUtils.isNotBlank(orderDetail.getBindTelephone())) {
                                        return orderDetail.getBindTelephone();
                                    }
                                    return null;
                                })
                                .orElse(MasterPhoneUtil.getSafeMasterPhone(orderWork.getCityId()))
                );
            }
            result = TmallApiInvoker.pushOrderDistribute(params);
        }
        // 天猫勤鸽店逻辑，同步工程师
        else {
            if (!isTmallWYG) {
                if (master == null) {
                    log.info("【{}】同步工程师信息失败，没找到对应工程师。 orderId：[{}]，masterId：[{}]",
                            TaobaoTmcConstants.NAME_TMALL, orderId, masterId);

                    result = new TmallApiInvokResult();
                    result.setSuccess(false);
                    result.setMsg(String.format("No Master found! masterId:[%d]", masterId));
                }
            }

             /*   else { 天猫勤鸽店逻辑，改为前置 --删除
                    params.setMasterName(master.getMasterName());
                    params.setMasterPhone(master.getMasterPhone());
                }*/
        }
        saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_DISTRIBUTE, result);
    }

    /**
     * 同步订单完成
     * @param orderWorkLogChange
     */
    @Override
    public void syncOrderComplete(OrderWorkLogChange orderWorkLogChange) {
        Long orderId = orderWorkLogChange.getOrderId();
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);
        ApiInvokParams params = new ApiInvokParams();

        // 是否是勤鸽渠道
        boolean isTmallWYG = Objects.equals(OrderConsts.CHANNEL_ID_TMALL_WYG, orderWork.getChannelId());
        // 临时  ----勤鸽暂时无需同步
        if (isTmallWYG) {
            return;
        }

        if (this.isSyncedSuccess(orderId, OrderStatusConsts.ORDER_STATUS_COMPLETE)) {
            return; // 已同步过成功的，不再同步了
        }

        // 管道疏通
        boolean isServCategPipe = Objects.equals(orderWork.getServCategId(), GlobalConsts.SERV_CATEG_PIPE);

        if (isTmallWYG && isServCategPipe) {
            OrderTmallExtend orderTmallExtend = orderTmallExtendBService.findOrderTmallExtendByOrderId(orderWork.getOrderId());
            if (orderTmallExtend != null) {
                params.setServiceCount(NumberUtil.isNotNullOrZero(orderTmallExtend.getServiceCount()) ?
                        orderTmallExtend.getServiceCount() : GlobalConsts.NO);
            } else {
                params.setServiceCount(GlobalConsts.NO);
            }
        }

        params.setChannleId(orderWork.getChannelId());
        params.setTmallOrderId(Long.parseLong(orderWork.getOuterId()));
        params.setZmnOrderId(orderId);
        TmallApiInvokResult result = TmallApiInvoker.pushOrderComplete(params);

        // 手动记录log
        if (isTmallWYG && isServCategPipe) {
            ZsOrderWorkVO orderWorkVO = BeanMapper.map(orderWork, ZsOrderWorkVO.class);
            String msg;
            if (result.isSuccess()) {
                msg = "核销同步成功";
            } else {
                msg = "核销同步失败";
            }
            OrderLog orderLog = buildOrderLog4Info(orderWorkVO, msg, OrderLogConsts.ORDER_LOG_TYPE_VERIFICATION);
            orderLogBService.save(orderLog);
        }

        saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_COMPLETE, result);
    }

    /**
     * 同步订单取消
     * @param orderWorkLogChange
     */
    @Override
    public void syncOrderCancel(OrderWorkLogChange orderWorkLogChange) {
        Long orderId = orderWorkLogChange.getOrderId();
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);

        ApiInvokParams params = new ApiInvokParams();
        params.setChannleId(orderWork.getChannelId());
        params.setTmallOrderId(Long.parseLong(orderWork.getOuterId()));
        params.setZmnOrderId(orderId);

        // 取消备注（原因），需要将手写备注和选项备注进行拼接
        OrderRemarkVO orderRemarkVO = orderRemarkBService.findOrderRemarkVO(orderId, orderId, OrderConsts.ORDER_REMARK_TYPE_CANCEL);
        List<String> remarkList = new LinkedList<>();
        if (StringUtils.isNotBlank(orderRemarkVO.getContent())) {
            remarkList.add(orderRemarkVO.getContent());
        }
        if (orderRemarkVO.getDetailVOList() != null) {
            for (OrderRemarkDetailVO item : orderRemarkVO.getDetailVOList()) {
                remarkList.add(item.getMapName());
            }
        }
        String remark = (remarkList.size() > 0) ? StringUtils.join(remarkList, "，") : null;
        params.setRemark(remark);

        TmallApiInvokResult result = TmallApiInvoker.pushOrderCancel(params);

        saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_CANCEL, result);
    }

    /**
     * 同步签到
     *
     * @param orderId
     */
    @Override
    public boolean syncSignIn(Long orderId, String mqMsgKey) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);

        ApiInvokParams params = new ApiInvokParams();
        params.setChannleId(orderWork.getChannelId());
        params.setTmallOrderId(Long.parseLong(orderWork.getOuterId()));
        params.setZmnOrderId(orderId);

        try {
            TmallApiInvokResult result = TmallApiInvoker.pushSignIn(params);
            // 保存同步记录
            OrderWorkLogChange orderWorkLogChange = new OrderWorkLogChange();
            orderWorkLogChange.setMqMsgKey(mqMsgKey);
            orderWorkLogChange.setOrderId(orderId);
            orderWorkLogChange.setChannelId(orderWork.getChannelId());
            orderWorkLogChange.setStatus(orderWork.getStatus());
            orderWorkLogChange.setResultStatus(orderWork.getResultStatus());
            saveSyncResult(orderWorkLogChange, OrderConsts.ORDER_OP_TYPE_SIGN_IN, result);

            if (result.isSuccess()) {
                return true;
            } else {
                log.info("失败原因" + result.getMsg());
                return false;
            }
        } catch (Exception e) {
            log.info(e.getMessage());
            return false;
        }
    }


    /**
     * 同步勤鸽派单
     *
     * @param orderId
     */
    @Override
    public TmallApiInvokResult syncOrderDistribute(Long orderId, String masterPhone, String masterName, Long stopOrderTypeCheckReason) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);
        OrderStatusParams params = new OrderStatusParams();
        params.setChannleId(orderWork.getChannelId());
        params.setTmallOrderId(Long.parseLong(orderWork.getOuterId()));
        params.setZmnOrderId(orderId);
        params.setMasterPhone(masterPhone);
        params.setMasterName(masterName);
        params.setStopOrderTypeCheckReason(stopOrderTypeCheckReason);
        TmallApiInvokResult result = TmallApiInvoker.pushOrderDistribute(params);

        // 保存同步记录
        OrderWorkLogChange orderWorkLogChange = new OrderWorkLogChange();
        orderWorkLogChange.setOrderId(orderId);
        orderWorkLogChange.setChannelId(orderWork.getChannelId());
        orderWorkLogChange.setStatus(orderWork.getStatus());
        orderWorkLogChange.setResultStatus(orderWork.getResultStatus());
        saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_DISTRIBUTE, result);

        if (!result.isSuccess()) {
            OrderTmallExtend orderTmallExtend = orderTmallExtendBService.findOrderTmallExtendByOrderId(orderWork.getOrderId());
            String msg = result.getMsg();
            if (msg.contains("工单不存在。请求入参")) {
                if (msg.indexOf("请求入参") != -1) {
                    msg = msg.substring(0, msg.indexOf("请求入参"));
                }
            }

            if (orderTmallExtend != null) {
                if (Objects.equals(orderTmallExtend.getVerification(), GlobalConsts.YES) && orderTmallExtend.getVerificationTime() != null) {
                    msg = "该订单已核销，无法进行派单。";
                }
            }
            result.setMsg(msg);
            //手动写日志
            ZsOrderWorkVO orderWorkVO = BeanMapper.map(orderWork, ZsOrderWorkVO.class);
            OrderLog orderLog = buildOrderLog4Info(orderWorkVO, "[操作派单]派单失败，" + msg, null);
            orderLogBService.save(orderLog);
        }

        return result;
    }

    /**
     * 回复消息预警
     * @param orderWarnReplyEvent
     */
    public void replyOrderWarn(OrderWarnReplyEvent orderWarnReplyEvent) {
        Long orderId = orderWarnReplyEvent.getOrderId();

        // 定义变量，存储需要回复的订单预警
        List<OrderWarn> unreplyOrderWarns = null;

        // 找出没有回复的订单预警
        List<OrderWarn> orderWarns = orderWarnBService.listOrderWarnsByOrderId(orderId);
        if (CollectionUtils.isNotEmpty(orderWarns)) {
            unreplyOrderWarns = orderWarns.stream()
                    .filter(item -> Objects.equals(item.getBizStatus(), OrderConsts.ORDER_WARN_STATUS_ACCEPT))
                    .collect(Collectors.toList());
        }

        // 回复订单预警，并更新预警信息的回复状态
        if (CollectionUtils.isNotEmpty(unreplyOrderWarns)) {
            for (OrderWarn item : unreplyOrderWarns) {
                TmallApiInvokResult taobaoApiInvokResult = TmallApiInvoker.replyOrderWarn(Long.valueOf(item.getOuterWarnId()), null);

                OrderWarn model = new OrderWarn();
                model.setWarnId(item.getWarnId());
                model.setLastSyncResponse(taobaoApiInvokResult.getMsg());
                if (taobaoApiInvokResult.isSuccess()) {
                    model.setBizStatus(OrderConsts.ORDER_WARN_STATUS_REPLIED);
                }
                orderWarnBService.modifyOrderWarnById(model);
            }
        }
    }

    /**
     * 保存状态同步结果信息
     * @param orderWorkLogChange
     * @param orderStatus
     * @param result
     */
    @SuppressWarnings("all")
    private void saveSyncResult(OrderWorkLogChange orderWorkLogChange, int orderStatus, TmallApiInvokResult result) {
        if (result == null) {
            return;
        }

        OrderNotifyLog orderNotifyLog = new OrderNotifyLog();
        orderNotifyLog.setMqMsgKey(orderWorkLogChange.getMqMsgKey());
        orderNotifyLog.setOrderId(orderWorkLogChange.getOrderId());
        orderNotifyLog.setChannelId(orderWorkLogChange.getChannelId());
        orderNotifyLog.setOrderStatus(orderWorkLogChange.getStatus());
        orderNotifyLog.setOrderResultStatus(orderWorkLogChange.getResultStatus());
        orderNotifyLog.setNotifyStatus(String.valueOf(orderStatus));
        orderNotifyLog.setType(OrderConsts.ORDER_NOTIFY_TYPE_CHANGE);
        orderNotifyLog.setNotifyTime(DateUtil.getNow());
        String orderStatusName = OrderStatusConsts.getOrderStatusName(orderStatus);
        if ("未知".equals(orderStatusName)) {
            orderStatusName = OrderConsts.getOperateTypeName(orderStatus);
        }
        orderNotifyLog.setNotifyResultMsg(String.format("[%s]-%s",
                orderStatusName, result.getMsg()));

        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setStatus(result.isSuccess() ? StatusConsts.STATUS_SUCCESS : StatusConsts.STATUS_ERROR);
        resultDTO.setData(orderNotifyLog);

        orderNotifyLogBService.saveNotifyLog(resultDTO);
    }

    /**
     * 判断状态是否已同步成功
     * @param orderId
     * @param orderStatus
     * @return
     */
    private boolean isSyncedSuccess(Long orderId, int orderStatus) {
        String status = String.valueOf(orderStatus);
        List<OrderNotifyLog> notifyLogs = orderNotifyLogBService.listByOrderId(orderId);
        if (!CollectionUtils.isEmpty(notifyLogs)) {
            for (OrderNotifyLog item : notifyLogs) {
                if (Objects.equals(item.getNotifyStatus(), status)
                        && Objects.equals(item.getNotifyResultStatus(), StatusConsts.STATUS_SUCCESS)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 去除已入库的预警（幂等校验）
     * @param originalWarns
     * @return
     */
    private List<UnservedWarningDTO> filterDuplicateUnserviceWarnings(List<UnservedWarningDTO> originalWarns) {
        List<UnservedWarningDTO> result = new LinkedList<>();

        // 排除掉已入库的预警，找出新增的预警数据
        List<Long> outerWarnIds = originalWarns.stream().map(item -> item.getId()).collect(Collectors.toList());
        List<OrderWarn> orderWarns = orderWarnBService.listOrderWarnsByOuterWarnIds(outerWarnIds);
        List<Long> duplicateOrderWarnIds = orderWarns.stream().map(item -> item.getOuterWarnId()).collect(Collectors.toList());

        for (UnservedWarningDTO dto : originalWarns) {
            if (!duplicateOrderWarnIds.contains(dto.getId())) {
                result.add(dto);
            }
        }

        return result;
    }


    /**
     * 保存预警信息
     * @param unservedWarningDTO
     */
    private void saveWarnInfo(UnservedWarningDTO unservedWarningDTO) {
        ZsOrderWorkVO orderWorkVO = null;

        // 找到预警消息中预警的工单
        // 预警消息中，当biz_type=1时，biz_id是工单id（即工单消息中的id字段，该字段保存在了工单表的outerId字段中）
        // 目前，淘宝只定义了biz_type=1的情况
        if (Objects.equals(1, unservedWarningDTO.getBizType())) {
            String outerId = Long.toString(unservedWarningDTO.getBizId());
            orderWorkVO = zsOrderWorkQueryBService.findOrderWorkByOuterId(outerId, null);
        }
        else {
            // TODO -lhl 如果淘宝方面扩展了biz_type（即biz_type!=1），biz_id的值是什么呢？如何通过该值找到系统中对应的订单呢？
        }

        if (orderWorkVO == null) {
            log.warn("【{}-消息-预警】系统中没找到对应的订单！ message:[{}]", TaobaoTmcConstants.NAME_TMALL,
                    JSON.toJSONString(unservedWarningDTO));
            return;
        }

        // 保存预警信息
        OrderWarn orderWarn = buildOrderWarn(orderWorkVO, unservedWarningDTO);
        orderWarnBService.addOrderWarn(orderWarn);

        // 存入工单日志
        OrderLog orderLog = buildOrderLog4Info(orderWorkVO, unservedWarningDTO.getContent(), null);
        orderLogBService.save(orderLog);
    }

    /**
     * 将预警信息封装成工单日志对象
     * @param orderWork
     * @param unservedWarningDTO
     * @return
     */
    @SuppressWarnings("all")
    private OrderWarn buildOrderWarn(ZsOrderWorkVO orderWork, UnservedWarningDTO unservedWarningDTO) {
        OrderWarn orderWarn = new OrderWarn();
        orderWarn.setChannelId(orderWork.getChannelId());
        orderWarn.setBizStatus(OrderConsts.ORDER_WARN_STATUS_ACCEPT);
        orderWarn.setCreater("系统");

        orderWarn.setOrderId(orderWork.getOrderId());
        orderWarn.setWorkId(orderWork.getWorkId());
        orderWarn.setOuterId(unservedWarningDTO.getBizId());
        orderWarn.setOuterWarnId(unservedWarningDTO.getId());
        orderWarn.setOuterData(JSON.toJSONString(unservedWarningDTO));

        return orderWarn;
    }

    /**
     * 将预警信息封装成工单日志对象
     * @param orderWork
     * @param unservedWarningDTO
     * @return
     */
    @SuppressWarnings("all")
    private OrderLog buildOrderLog4Info(ZsOrderWorkVO orderWork, String content, Integer logType) {
        OrderLog orderLog = new OrderLog();

        orderLog.setOrderId(orderWork.getOrderId());
        orderLog.setWorkId(orderWork.getWorkId());
        orderLog.setContent(content);

        if (NumberUtil.isNotNullOrZero(logType)) {
            orderLog.setType(logType);
            orderLog.setTypeName(OrderLogConsts.getOrderLogTypeName(logType));
        } else {
            orderLog.setType(OrderLogConsts.ORDER_LOG_TYPE_CHANNEL_REMARK);
            orderLog.setTypeName(OrderLogConsts.getOrderLogTypeName(OrderLogConsts.ORDER_LOG_TYPE_CHANNEL_REMARK));
        }

        orderLog.setBeforeStatus(orderWork.getStatus());
        orderLog.setBeforeStatusName(OrderStatusConsts.getWorkStatusName(orderWork.getStatus()));
        orderLog.setBeforeResultStatus(orderWork.getResultStatus());
        orderLog.setBeforeResultStatusName(OrderStatusConsts.getWorkResultStatusName(orderWork.getResultStatus()));
        orderLog.setAfterStatus(orderWork.getStatus());
        orderLog.setAfterStatusName(OrderStatusConsts.getWorkStatusName(orderWork.getStatus()));
        orderLog.setAfterResultStatus(orderWork.getResultStatus());
        orderLog.setAfterResultStatusName(OrderStatusConsts.getWorkResultStatusName(orderWork.getResultStatus()));

        OrderWorkLogUtils.processOrderLogOperater(orderLog, null);

        return orderLog;
    }
    /**
     * 查询领单工程师信息
     * @param orderId
     * @param masterId
     */
    private OrderMaster findOrderMaster(Long orderId, Integer masterId) {
        List<OrderMaster> masterList = orderMasterService.listMasterByWorkId(orderId, orderId);
        if (masterList == null) {
           return null;
        }

        for (OrderMaster item : masterList) {
            if (item.getMasterId().equals(masterId)) {
                return item;
            }
        }

        return null;
    }
}
